package com.situ.controller;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alipay.api.AlipayApiException;
import com.situ.bean.*;
import com.situ.service.*;
import com.situ.util.LayData;
import com.situ.util.PaymentUtil;
import com.situ.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.nio.Buffer;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Controller

public class HomeController {
    @RequestMapping("index")
        public String index() {
            return "index.html"; // 返回到 index.html
        }

    @RequestMapping("home")
    public String home() {
        return "home.html"; // 返回到 index.html
    }




    @RequestMapping("index.html")
    public String indexht() {
        return "index"; // 返回到 index.html
    }
    @RequestMapping("user.html")
    public String user() {
        return "user.html"; // 返回到 index.html
    }




    @RequestMapping("index-two.html")
    public String indextwo() {
        return "index-two"; // 返回到 index.html
    }


    @RequestMapping("about.html")
        public String about() {
            return "about"; // 返回到 about.html
        }

        @RequestMapping("blog.html")
        public String blog() {
            return "blog.html"; // 返回到 blog.html
        }

        @RequestMapping("blog-details.html")
        public String blogDetails() {
            return "blog-details"; // 返回到 blog-details.html
        }



        @Autowired
        ICartService cartService ;
        //访问购物车，带着session访问
        @RequestMapping("cart.html")

        public String cart(HttpSession session, Model model) {
        User login = (User) session.getAttribute(SYS.UPLOAD_USER);
        List<Cart> cart= cartService.getcart(login);
         List<Product>products=cartService.getProducts(login);
         System.out.println("数据返回给购物车html");
         //System.out.println(cartService.getcart(login).toString());

        // System.out.println(cartService.getProducts(login).toString());
         List<CartProduct> cartProducts =new ArrayList<>();
         for(int i=0;i<cart.size();i++){
              CartProduct a=new CartProduct();
              a.setNumber(cart.get(i).getNumber());
               a.setUserid(cart.get(i).getUserid());
               a.setProductid(cart.get(i).getProductid());
               for(int j=0;j<products.size();j++){
                   if(cart.get(i).getProductid()==products.get(j).getId()){

                       a.setImgurl(products.get(j).getImgurl());
                       a.setName(products.get(j).getName());
                       a.setPrice(products.get(j).getPrice());

                   }
               }
               cartProducts.add(a);

         }
           model.addAttribute("cartProducts",cartProducts);

            return "cart"  ; // 返回到 cart.html
        }
     @Autowired
      IUseraddressService useraddressService;

        @RequestMapping("check-out.html")
        public String checkOut(HttpSession session, Model model) {
            User login = (User) session.getAttribute(SYS.UPLOAD_USER);
            //获取了User数据
            System.out.println("支付界面"+login.toString());
            if(login!=null&&useraddressService.getAddress(login)!=null) {
                Useraddress address = useraddressService.getAddress(login);
                model.addAttribute( SYS.UPLOAD_Address,address);
                System.out.println("地址" + address.toString());

            }

            Result result= (Result) session.getAttribute(SYS.Result);
           //result中有 productid 和quantiy, price
            //订单表上要有，product.name ,quanntiy ,quanty*price
            List<Orderinfo> orderinfos = new ArrayList<>();

            if(result!=null){
                for(int i=0;i<result.getItems().size();i++){
                        List item = result.getItems();
                       System.out.println(item.get(i).toString());
                        HashMap a= (HashMap) item.get(i);
                        System.out.println(a.get("productid").toString());
                        System.out.println(a.get("quantity").toString());
                        System.out.println(a.get("price").getClass());
                        Product product = productService.getProductById(Integer.parseInt(a.get("productid").toString()));
                        System.out.println(product.toString());
                         Orderinfo orderinfo=new Orderinfo(product.getId(), BigDecimal.valueOf(Double.parseDouble(product.getPrice())),product.getName(),product.getImgurl());
                         orderinfo.setNumber(Integer.parseInt(a.get("quantity").toString()));
                         System.out.println(orderinfo.toString());
                         orderinfos.add(orderinfo);


                }
            }

            model.addAttribute("orderinfos",orderinfos);

            return "check-out"; // 返回到 check-out.html
        }


    @Autowired
     IOrderService orderService;

        //提交订单
    @RequestMapping("place-order")
        @ResponseBody
        public LayData placeOrder(HttpSession session, @RequestBody Useraddress useraddress) {
            useraddress.setUserid(((User) session.getAttribute(SYS.UPLOAD_USER)).getId());
            System.out.println(useraddress.toString());
            useraddressService.addupdateAddress(useraddress);

            Order order=new Order();
            order.setUserid(((User) session.getAttribute(SYS.UPLOAD_USER)).getId());
            //获取当前时间
             order.setAddtime(new Date());
             System.out.println(order.toString()+"测试时间和id");
            //先插入数据order表
          //生成订单编码,随机生成订单编号
              String code = "GSHOP"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+new Random().nextInt(1000);
              order.setCode(code);
            if(orderService.addorder(order)){
                System.out.println("订单插入成功");

            }else{
                System.out.println("订单插入失败");
            }

            int id =  orderService.getorder(order).getId();


            Result result= (Result) session.getAttribute(SYS.Result);
            double total=0;
            LayData layout = new LayData();
            if(result!=null){
                for(int i=0;i<result.getItems().size();i++){
                    List item = result.getItems();
                    System.out.println(item.get(i).toString());
                    HashMap a= (HashMap) item.get(i);
                    Product product = productService.getProductById(Integer.parseInt(a.get("productid").toString()));
                    Orderinfo orderinfo=new Orderinfo(product.getId(), BigDecimal.valueOf(Double.parseDouble(product.getPrice())),product.getName(),product.getImgurl());
                    orderinfo.setNumber(Integer.parseInt(a.get("quantity").toString()));
                    orderinfo.setOrderid(id);
                    orderService.addorderinfo(orderinfo);
                    total+=Double.parseDouble(product.getPrice())*Integer.parseInt(a.get("quantity").toString());
                }
                order.setMoney(BigDecimal.valueOf(total));
                order.setOrderaddress(useraddress.getProvince()+useraddress.getCity()+useraddress.getArea()+useraddress.getAddress());
                order.setState("下单成功");
                orderService.updateorder(order);
                layout.setMsg("下单成功");
                layout.setCode(0);
                layout.setPcode(code);
            }
            String url=null;
               PaymentUtil paymentUtil=new PaymentUtil();
                 try {
                   url=paymentUtil.code(order);
                 }
                 catch (AlipayApiException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
              BufferedImage image = QrCodeUtil.generate(url, 300, 300);
              String qrcode = ImgUtil.toBase64(image,"png");
              layout.setQrCode(qrcode);
            return layout;
        }




    @RequestMapping("contact.html")
        public String contact() {
            return "contact"; // 返回到 contact.html
        }


        @RequestMapping("faq.html")
        public String faq() {
            return "faq"; // 返回到 faq.html
        }


        @RequestMapping("login.html")
        public String login() {
            return "login"; // 返回到 login.html
        }

   @Autowired
   IProductService productService;
        @RequestMapping("product-category.html")
        public String productCategory(Model model) {
            System.out.println(productService.getAllProducts().toString());
          if(model.getAttribute("products")==null&&productService.getAllProducts()!=null) {
              model.addAttribute("products", productService.getAllProducts());

              model.addAttribute("currentPage", 1); // 当前页码
              // 总页数
              // 总数据量

          }

            return "product-category"; // 返回到 product-category.html
        }


        @RequestMapping("product-two-details.html")
        public String productTwoDetails(HttpSession session,Model model) {
            Product product = (Product) session.getAttribute("product");
            System.out.println("商品展示");
            System.out.println(product);
            model.addAttribute("product",product);
            return "product-two-details"; // 返回到 product-two-details.html
        }


        @RequestMapping("registration.html")
        public String registration() {
            return "registration"; // 返回到 registration.html
        }


        @RequestMapping("wishlist.html")
        public String wishlist() {
            return "wishlist"; // 返回到 wishlist.html
        }


    @RequestMapping("admin.html")
    public String admin() {
        return "admin"; // 返回到 wishlist.html
    }








    }


